import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;


public class ParDom {
	private DocumentBuilder dbud;
	Document doc;
	Element root;
	String nazwa=new String("nazwa");
	String cena=new String("cena");
	FileOutputStream stream;
	
	public ParDom(String source, String wynik){
		DocumentBuilderFactory fac= DocumentBuilderFactory.newInstance();
		try {
			dbud = fac.newDocumentBuilder();
			File f = new File(source);
			File z =new File(wynik);
			f.createNewFile();
			 stream =new FileOutputStream(z);
			doc = dbud.parse(f);
			root = doc.getDocumentElement();
			NodeList list =root.getChildNodes();
			if(list.getLength()>0) 
			for(int i=0; i<list.getLength();++i){
				Node n=list.item(i);
				if( n instanceof Element){
					Element e=(Element)n;
					pl(e.getAttribute("nazwa").trim());
				}
				print(list.item(i));
				pln();pln();
			}
			
			
			
			
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}

	private void print(Node r) throws DOMException, IOException {
		Node tempr=r;
		//pl(r.getTagName());
		Element e=null;
		String name=null;

		NodeList list =tempr.getChildNodes();
		if(list.getLength()>0) 
		for(int i=0; i<list.getLength();++i){
			Node n=list.item(i);
			print(n);
			if( n instanceof Element){
				e=(Element)n;
				name=e.getTagName();
				//p("-----------"+name+"---------");
				if(name.equals(nazwa))
					p("\t"+name+": "+e.getTextContent().trim());
				if(name.equals(cena))
					pl("\t"+name+": "+e.getTextContent().trim());
			}
		}
		//if(e!=null && name.equals(new String("produkt")))pln();
	}
	
	
	
	private void pt(Object o){
		System.out.print(o.toString());
	}
	private void ptl(Object o){
		System.out.println(o.toString());
	}
	private void pl(String s) throws IOException{
		System.out.println(s);
		s=s+"\n";
		stream.write(s.getBytes());
	}
	private void p(String s) throws IOException{
		System.out.print(s);
		stream.write(s.getBytes());
	}
	private void pln() throws IOException{
		System.out.println("");
		String s= new String("\n");
		stream.write(s.getBytes());
	}

}
